package com.ruoyi.modularbusiness.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.modularbusiness.domain.*;
import com.ruoyi.modularbusiness.domain.VO.AubitTypeVo;
import com.ruoyi.modularbusiness.domain.VO.FormRtbVo;
import com.ruoyi.modularbusiness.mapper.AubitFieldMapper;
import com.ruoyi.modularbusiness.mapper.AubitTypeMapper;
import com.ruoyi.modularbusiness.service.IAubitFieldbodyService;
import com.ruoyi.modularbusiness.service.IFormbodySecondaryService;
import com.ruoyi.modularbusiness.service.IFormbodyService;
import com.ruoyi.modularbusiness.util.ExportExcel;
import com.ruoyi.system.api.RemotePublicService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.modularbusiness.service.IFormrecordingService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 表单记录Controller
 *
 * @author liuzheng
 * @date 2023-01-05
 */
@RestController
@RequestMapping("/formrecording")
public class FormrecordingController extends BaseController {

    @Autowired
    private IFormrecordingService formrecordingService;

    @Autowired
    private IFormbodyService formbodyService;

    @Autowired
    private IFormbodySecondaryService formbodySecondaryService;

    @Autowired
    private IAubitFieldbodyService aubitFieldbodyService;

    @Autowired
    private RemotePublicService remotePublicService;

    @Autowired
    private AubitFieldMapper aubitFieldMapper;

    @Autowired
    private IFormrecordingService iFormrecordingService;

    @ApiOperation(notes = "", value = "topid 查询签核信息")
    @PostMapping("/getauditmloud")
    public List<AubitTypeVo> getauditmloud(@RequestBody int topid) {
        return formrecordingService.getauditmloud(topid);
    }

    @ApiOperation(notes = "", value = "afbd_number 查询签核信息")
    @GetMapping("/getauditmloud2")
    public TableDataInfo getauditmloud2(AubitTypeVo afbd_number) {
        startPage();
        List<AubitTypeVo> list = formrecordingService.getauditmloud2(afbd_number);
        return getDataTable(list);
    }

    @GetMapping("/auditmolud_sels")
    public int auditmolud_sels(AubitField afbd_number) {
        int randomNum = (int) ((Math.random() * 9 + 1) * 100000);
        afbd_number.setAtpId(Long.parseLong(randomNum+""));
        return aubitFieldMapper.updateAubitField(afbd_number);
    }

    @ApiOperation(notes = "", value = "签核模型待签核查询")
    @PostMapping("/auditmolud_sel")
    List<FormRtbVo> auditmolud_sel(@RequestBody String code) {
        return formrecordingService.auditmolud_sel(code);
    }

    @ApiOperation(notes = "", value = "批量查询 粗略表单信息")
    @PostMapping("/getformrough")
    public List<FormRtbVo> getformrough(@RequestBody List<FormRtbVo> frid) {
        return formrecordingService.getformrough(frid);
    }

    @ApiOperation(notes = "", value = "保安查询接口")
    @PostMapping("/get_baoan")
    public AjaxResult get_baoan(Long id) {
        return success(formrecordingService.get_baoan(id));
    }

    /**
     * 查询表单内容
     *
     * @param formrecording 类条件
     */
    @ApiOperation(notes = "", value = "查询表单内容")
    @PostMapping("/GetFormrecordingByFrid")
    public AjaxResult GetFormrecordingByFrid(@RequestBody Formrecording formrecording) {
        return success(formrecordingService.GetFormrecordingByFrid(formrecording));
    }

    /**
     * 工号 查询当前需要签核的表单
     *
     * @param JO 工号
     */
    @ApiOperation(notes = "", value = "查询未审核表单")
    @PostMapping("/selform_audit")
    public List<Formrecording> selform_audit(@RequestBody JSONObject JO) {
        String numbers = JO.get("numbers").toString();
        return formrecordingService.selform_audit(numbers);
    }

    /**
     * id 查询用户当下所有表单  返回状态字段
     */
    @ApiOperation(notes = "", value = "表单历史记录")
    @PostMapping("/seluserform_all_state")
    public List<FormRtbVo> seluserform_all_state() {

        int userid = Integer.parseInt(SecurityUtils.getUserId() + "");
        return formrecordingService.seluserform_all_state(userid);
    }

    /**
     * 记录 id 调出 企业微信通知数据
     */
    @ApiOperation(notes = "", value = "记录 id 调出 企业微信通知数据")
    @PostMapping("/get_trid_notice")
    public List<AubitTypeVo> get_trid_notice(Long topid) {
        return formrecordingService.get_trid_notice(topid);
    }

    /**
     * 新增表单记录
     */
//    @RequiresPermissions("modularbusiness:formrecording:list")
    @ApiOperation(notes = "{\"userid\": \"\",\"typeid\": \"\",\"numbers\": \"\",\"datalist\": \"\"}", value = "表单记录新增")
    @PostMapping("/insert_add")
    public AjaxResult insert_add(@RequestBody JSONObject JO) {
        Formrecording formrecording = new Formrecording();
        formrecording.setFrtypeid(Long.parseLong(JO.get("typeid").toString()));
        formrecording.setUserid(JO.get("userid").toString());
        formrecording.setNumbers(JO.get("numbers").toString());
        formrecordingService.insertFormrecording(formrecording);
        List<Formbody> list = new ArrayList<Formbody>();
        JSONArray datalit = JSONArray.parseArray(JSON.toJSONString(JO.get("datalist")));
        for (int i = 0; i < datalit.size(); i++) {
            Formbody formbody = new Formbody();
            formbody.setFrid(Long.parseLong(formrecording.getFrid().toString()));
            formbody.setFfid(Long.parseLong(datalit.getJSONObject(i).get("ffid").toString()));
            if (datalit.getJSONObject(i).get("identify").toString().equals("no")) {
                int randomNum = (int) ((Math.random() * 9 + 1) * 100000);
                formbody.setBodyTxt(randomNum + "");
            } else {
                formbody.setBodyTxt(datalit.getJSONObject(i).get("txt").toString());
            }
            formbody.setAuditState(Integer.parseInt(datalit.getJSONObject(i).get("tf").toString()));
            list.add(formbody);
        }
//         执行
        Long t1 = formbodyService.batchSave(list);
        Long t2 = null;
        Long t3 = null;
//        // 二级表字段
        List<FormbodySecondary> Secondarylist = new ArrayList<FormbodySecondary>();
        JSONArray secondarylist = JSONArray.parseArray(JSON.toJSONString(JO.get("secondarylist")));
        if (secondarylist.size() > 0) {
            for (int i = 0; i < secondarylist.size(); i++) {
                FormbodySecondary formbodySecondary = new FormbodySecondary();
                formbodySecondary.setFrid(Long.parseLong(formrecording.getFrid().toString()));
                formbodySecondary.setFfid(Long.parseLong(secondarylist.getJSONObject(i).get("ffid").toString()));
                formbodySecondary.setSecondarySort(Long.parseLong(secondarylist.getJSONObject(i).get("secondarySort").toString()));
                if (secondarylist.getJSONObject(i).get("identify").toString().equals("no")) {
                    int randomNum = (int) ((Math.random() * 9 + 1) * 100000);
                    formbodySecondary.setBodyTxt(randomNum + "");
                } else {
                    formbodySecondary.setBodyTxt(secondarylist.getJSONObject(i).get("txt").toString());
                }
                formbodySecondary.setAuditState(Integer.parseInt(secondarylist.getJSONObject(i).get("tf").toString()));
                Secondarylist.add(formbodySecondary);
            }
            // 执行
            t2 = formbodySecondaryService.batchSave(Secondarylist);
        }

        // 签核逻辑   待测试
        List<AubitFieldbody> AubitFieldbodylist = new ArrayList<>();
        JSONArray aubitFieldbodylist = JSONArray.parseArray(JSON.toJSONString(JO.get("aubitlist")));
        if (aubitFieldbodylist.size() > 0) {
//            System.out.println("签核数据" + aubitFieldbodylist);
            for (int i = 0; i < aubitFieldbodylist.size(); i++) {
                AubitFieldbody aubitFieldbody = new AubitFieldbody();
                aubitFieldbody.setTopid(Long.parseLong(formrecording.getFrid().toString()));
                aubitFieldbody.setAtpId(Long.parseLong(aubitFieldbodylist.getJSONObject(i).get("atp_id").toString()));
                aubitFieldbody.setAfdId(Long.parseLong(aubitFieldbodylist.getJSONObject(i).get("afd_id").toString()));
                aubitFieldbody.setAfbdNumber(aubitFieldbodylist.getJSONObject(i).get("afd_auditbody").toString());
                aubitFieldbody.setAfbdState("1");
                AubitFieldbodylist.add(aubitFieldbody);
            }
            // 执行
            t3 = aubitFieldbodyService.batchSave(AubitFieldbodylist);
        }
        //  企业微信通知
        if (aubitFieldbodylist.getJSONObject(0).get("qywx") != null) {

            List<AubitTypeVo> listss = iFormrecordingService.get_trid_notice(formrecording.getFrid());
            if (listss.size() > 0) {
                String urls = "pages/login/login?url=pages/formlist/formbody/formbody!name," + listss.get(0).getName() +
                        "-%frid," + formrecording.getFrid().toString() + "-%abbreviated," + listss.get(0).getAbbreviated() + "-%fbid," + listss.get(0).getAfbd_id() + "-%type,3-%times," + listss.get(0).getCreate_time();
//                System.out.println(urls);
                JSONObject jo = new JSONObject();
                jo.put("url", urls);
                jo.put("username", listss.get(0).getUsername());
                jo.put("to", listss.get(0).getQywx());
                jo.put("deptname", listss.get(0).getDept_name());
                jo.put("type", listss.get(0).getName());
                jo.put("creatime", listss.get(0).getCreate_time());
                remotePublicService.qywxxcx_msg_push(jo, SecurityConstants.INNER);
            }

//            JSONObject jo=new JSONObject();
//            jo.put("username",JO.get("username").toString());
//            jo.put("to",aubitFieldbodylist.getJSONObject(0).get("qywx").toString());
//            jo.put("deptname",aubitFieldbodylist.getJSONObject(0).get("atp_jc").toString());
//            jo.put("type",aubitFieldbodylist.getJSONObject(0).get("atp_name").toString());
//            remotePublicService.qywxxcx_msg_push(jo, SecurityConstants.INNER);
        }
        return success("t1" + t1 + "t2" + t2 + "t3" + t3);
    }


    /**
     * 查询表单记录列表
     */
//    @RequiresPermissions("modularbusiness:formrecording:list")
    @GetMapping("/list")
    public TableDataInfo list(Formrecording formrecording) {
        startPage();
        List<Formrecording> list = formrecordingService.selectFormrecordingList(formrecording);
        return getDataTable(list);
    }

    @GetMapping("/list2")
    public TableDataInfo list2(Formrecording formrecording) {
        startPage();
        List<Formrecording> list = formrecordingService.selectFormrecordingList2(formrecording);
        return getDataTable(list);
    }

    /**
     * 导出表单记录列表
     */
//    @RequiresPermissions("modularbusiness:formrecording:export")
    private void processFormRecording(List<Formrecording> list) {
        for (int i = 0; i < list.size(); i++) {
            Formrecording formrecording1 = new Formrecording();
            formrecording1.setFrid(list.get(i).getFrid());
            list.get(i).setFormRtbVo(formrecordingService.GetFormrecordingByFrid(formrecording1));
        }
    }

    @Log(title = "表单记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Formrecording formrecording) {
        List<Formrecording> list = formrecordingService.selectFormrecordingList(formrecording);
        processFormRecording(list);
        ExcelUtil<Formrecording> util = new ExcelUtil<Formrecording>(Formrecording.class);
        util.exportExcel(response, list, "表单记录数据");
    }

    @Log(title = "表单记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export2")
    public void export2(HttpServletResponse response, Formrecording formrecording) {
        List<Formrecording> list = formrecordingService.selectFormrecordingList2(formrecording);
        processFormRecording(list);
//        System.out.println(list);
        ExcelUtil<Formrecording> util = new ExcelUtil<Formrecording>(Formrecording.class);
        util.exportExcel(response, list, "表单记录数据");
    }

    //    @RequiresPermissions("modularbusiness:formrecording:export")
    private void processData(List<Formrecording> list, List<Map<String, Object>> data, List<String> column) {
        for (int i = 0; i < list.size(); i++) {
            Formrecording formrecording = list.get(i);
            Formrecording formrecording1 = new Formrecording();
            formrecording1.setFrid(formrecording.getFrid());
            List<FormRtbVo> formRtbVo = formrecordingService.GetFormrecordingByFrid(formrecording1);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("工号", formrecording.getNumbers());
            dataMap.put("单据类型", formrecording.getName());
            dataMap.put("申请人", formrecording.getNick_name());
            for (int p = 0; p < formRtbVo.size(); p++) {
                dataMap.put(formRtbVo.get(p).getName(), formRtbVo.get(p).getBody_txt());
            }
            data.add(dataMap);
            if (i == 0) {
                for (int j = 0; j < formRtbVo.size(); j++) {
                    column.add(formRtbVo.get(j).getName());
                }
            }
        }
    }

    @Log(title = "表单记录", businessType = BusinessType.EXPORT)
    @PostMapping("/exports")
    public void exports(HttpServletRequest request, HttpServletResponse response, Formrecording formrecording) {
        List<Formrecording> list = formrecordingService.selectFormrecordingList(formrecording);
        List<Map<String, Object>> data = new ArrayList<>();
        List<String> column = new ArrayList<>();
        column.add("工号");
        column.add("单据类型");
        column.add("申请人");
        processData(list, data, column);
        ExportExcel.exportExcel("表单记录数据", column, data, request, response);
    }

    @Log(title = "表单记录", businessType = BusinessType.EXPORT)
    @PostMapping("/exports2")
    public void exports2(HttpServletRequest request, HttpServletResponse response, Formrecording formrecording) {
        List<Formrecording> list = formrecordingService.selectFormrecordingList2(formrecording);
        List<Map<String, Object>> data = new ArrayList<>();
        List<String> column = new ArrayList<>();
        column.add("工号");
        column.add("单据类型");
        column.add("申请人");
        processData(list, data, column);
        ExportExcel.exportExcel("表单记录数据", column, data, request, response);
    }

    /**
     * 获取表单记录详细信息
     */
    @RequiresPermissions("modularbusiness:formrecording:query")
    @GetMapping(value = "/{frid}")
    public AjaxResult getInfo(@PathVariable("frid") Long frid) {
        return success(formrecordingService.selectFormrecordingByFrid(frid));
    }

    /**
     * 新增表单记录
     */
    @RequiresPermissions("modularbusiness:formrecording:add")
    @Log(title = "表单记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Formrecording formrecording) {
        return toAjax(formrecordingService.insertFormrecording(formrecording));
    }

    /**
     * 修改表单记录
     */
    @RequiresPermissions("modularbusiness:formrecording:edit")
    @Log(title = "表单记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Formrecording formrecording) {
        return toAjax(formrecordingService.updateFormrecording(formrecording));
    }

    /**
     * 删除表单记录
     */
    @RequiresPermissions("modularbusiness:formrecording:remove")
    @Log(title = "表单记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{frids}")
    public AjaxResult remove(@PathVariable Long[] frids) {
        return toAjax(formrecordingService.deleteFormrecordingByFrids(frids));
    }
}
